package muhtar.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import muhtar.common.MuhtarConstants;
import muhtar.service.Muhtar;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

public class RequestHandler extends AbstractHandler
{	
	private Muhtar muhtar;
	
	public RequestHandler() throws IOException {
		muhtar = new Muhtar();
	}
	
	private void processEditorRequest(String target, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		String key = request.getParameter("key");
		String value = request.getParameter("value");
		if (key == null || "".equals(key)) {
			throw new IOException("invalid key: " + key);
		}
		if ("".equals(value)) {
			value = null;
		}
		key = "/" + key;		
		muhtar.set(key, value);
		System.out.println("SET " + key + "=" + value);
		// return to editor
		response.getWriter().println(muhtar.get(MuhtarConstants.ADMIN_COMMAND_EDITOR));
	}
	
	private void processRequest(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException 
	{
		if (request.getQueryString() == null) {
			String value = muhtar.get(target);
			if (value != null) {
				response.getWriter().println(value);
			}
			System.out.println("GET " + target);
		} else {
			String value = request.getQueryString();
			if ("".equals(value)) {
				value = null;
			}
			muhtar.set(target, value);
			System.out.println("SET " + target + "=" + value);
		}
	}

	private void setConnectionProperties(HttpServletResponse response)
	{
		response.setHeader("Cache-Control", "private, max-age=3600");
		response.setContentType("text/html;charset=utf-8");
		response.setStatus(HttpServletResponse.SC_OK);
	}
	
	public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		setConnectionProperties(response);
		baseRequest.setHandled(true);
		
		if ("GET".equals(request.getMethod())) {
			processRequest(target, baseRequest, request, response);		
		} else if ("POST".equals(request.getMethod()) && MuhtarConstants.ADMIN_COMMAND_EDITOR.equals(target)) {
			processEditorRequest(target, request, response);
		} else {
			response.sendError(400);
		}
	}
}
